import express from "express";

import { db } from "../database.js";
import { validate, validators } from "../validate.js";
import { makePassword, checkPassword } from "../utils.js";
import { auth } from "../auth.js";

const router = express.Router();

// 实现用户注册功能
router
  .post(
    "/register",
    validate(
      validators.username,
      validators.password,
      validators.confirmPassword,
      validators.nickname
    ),
    async (req, res) => {
      const { username, password, nickname } = req.body;
      // 判定用户名是否已存在
      const user =
        await db.findOne`select * from user where username = ${username}`;
      if (user) {
        return res.json({ success: false, message: "用户名已存在" });
      }
      // 插入用户信息
      const newUser =
        await db.insert`insert into user (username, password, nickname)
        values (${username}, ${makePassword(password)}, ${nickname})`;
      // 注册成功
      res.json({ success: true, object: newUser });
    }
  )
  // 实现登录功能
  .post(
    "/login",
    validate(validators.username, validators.password),
    async (req, res) => {
      const { username, password } = req.body;
      const user =
        await db.findOne`select * from user where username = ${username}`;
      if (user && checkPassword(password, user.password)) {
        // 保存用户ID到session
        req.session.userId = user.id;
        return res.json({ success: true, object: user });
      }
      res.json({ success: false, message: "用户名或密码错误" });
    }
  );

// 验证用户登录状态，保护以后注册的路由！
router.use(auth);

// 用户登出
router
  .get("/logout", (req, res) => {
    req.session.destroy();
    res.json({ success: true, message: "用户已退出登录" });
  })
  // 获取登录用户信息
  .get("/user/info", async (req, res) => {
    const user =
      await db.findOne`select * from user where id = ${req.session.userId}`;
    res.json({ success: true, object: user });
  })
  .put(
    "/user/change-password",
    validate(
      validators.oldPassword,
      validators.password,
      validators.confirmPassword
    ),
    async (req, res) => {
      const { oldPassword, password } = req.body;
      const user =
        await db.findOne`select * from user where id = ${req.session.userId}`;
      if (!checkPassword(oldPassword, user.password)) {
        return res.json({ success: false, message: "原密码错误" });
      }
      await db.update`update user set password = ${makePassword(password)}
        where id = ${req.session.userId}`;
      res.json({ success: true, message: "密码修改成功" });
    }
  );

export default router;
